package org.itboys.shop.web;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.itboys.framework.spring.controller.BaseController;
import org.itboys.seller.constant.SellerConstants;
import org.itboys.seller.dto.SellerMenuDTO;
import org.itboys.seller.entity.SellerMenu;
import org.itboys.seller.entity.SellerUser;
import org.itboys.seller.service.SellerMenuService;
import org.itboys.seller.service.SellerUserService;
import org.itboys.seller.utils.SellerSessionHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

@RestController
@RequestMapping("/shop")
public class ShopIndexController extends BaseController{

	@Autowired
	private SellerUserService sellerUserService;
	@Autowired
	private SellerMenuService sellerMenuService;
	
	/**
	 * 首页跳转
	 * @param response
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/index","","/"})
	public ModelAndView index(HttpServletResponse response, Model model)
			throws Exception {
		
		Long userId = SellerSessionHolder.getSellerUserId();
		
		if (userId == null) {
			return new ModelAndView("redirect:/seller/login");
		} else {
			
			final SellerUser user = sellerUserService.getById(userId);

			Map<String, Object> param = Maps.newHashMapWithExpectedSize(0);
			List<SellerMenu> menus = sellerMenuService.list(param);

			final List<SellerMenu> roleMenus = (user.getType() == SellerConstants.TYPE_SUPER) ? 
					null : new ArrayList<SellerMenu>(menus.size());
			
			if (user.getType() != SellerConstants.TYPE_SUPER) {
				for (SellerMenu am : menus) {
					if (user.getMenuIds().contains(am.getId())) {
						roleMenus.add(am);
					}
				}
			}
			
			List<SellerMenu> allowMenus = user.getType() == SellerConstants.TYPE_SUPER ? menus : roleMenus;

			List<SellerMenuDTO> menuDTOList = Lists.newArrayList();
			for (SellerMenu menu : allowMenus) {
				if (menu.getParentId().equals(0L)) {
					SellerMenuDTO dto = new SellerMenuDTO();
					dto.setMenu(menu);
					menuDTOList.add(dto);
				}
			}
			for (SellerMenuDTO dto : menuDTOList) {
				for (SellerMenu menu : allowMenus) {
					if (menu.getParentId().equals(dto.getMenu().getId())) {
						dto.getChildren().add(menu);
					}
				}
			}
			model.addAttribute("allowMenus", menuDTOList);

			model.addAttribute("sellerUserDTO", user);
			return new ModelAndView("/index");
		}
	}
}
